<?php
    session_start();
    include('conn.php');
    include('verify_user.php');
    require 'anti_csrf.php';
    
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        if (!isset($_POST['CSRFName'])) {
            trigger_error("No CSRFName found, probable invalid request.",E_USER_ERROR);
        }
        $name =$_POST['CSRFName'];
        $token=$_POST['CSRFToken'];
        if (!csrfguard_validate_token($name, $token)) {
            trigger_error("Invalid CSRF token.",E_USER_ERROR);
        }
	
        $shop_name = $_POST['newshop_shopname'];
        $shop_category = $_POST['newshop_category'];
        $shop_desc = $_POST['newshop_desc'];
        $delivery_methods = $_POST['newshop_delivery'];
	$shop_owner = $_POST['newshop_shopowner'];
	
	include('validate_shop_inputs.php');
	
	if ($shop_owner != $cur_user) {
	    die('You have no right to do so');
	}
	
	$query = "SELECT max(id) id FROM log";
	$rs = pg_query($con, $query) or die("Could not excute query");
	$row = pg_fetch_assoc($rs);
	$id = $row['id'] + 1;
	
        pg_prepare($con, 'prepare4', 'INSERT INTO shops (shop_name, shop_owner, shop_desc, delivery_methods, shop_category) VALUES ($1, $2, $3, $4, $5)') or die("Could not prepare statement");
        pg_prepare($con, 'log_prepare3', 'INSERT INTO log (username, operation, object, time, id) VALUES ($1, $2, $3, $4, $5)') or die('Could not prepare log');
	$res1 = pg_execute($con, 'prepare4', array($shop_name, $shop_owner, $shop_desc, $delivery_methods, $shop_category)) or die("Could not execute query");
	$res2 = pg_execute($con, 'log_prepare3', array($cur_user, 'Creat Shop', $shop_name, date('Y-m-d'), $id)) or die('Could not execute log');
	
	if($res1 && $res2) {
	    pg_query('COMMIT') or die('Could not commit');
	} else {
	    pg_query('ROLLBACK') or die('Could not rollback');
	}
	
        pg_close($con);
	header('Location: http://'.$_SERVER['HTTP_HOST'].'/php/shop.php?id=' . $_SESSION['username'].'&shop='.$shop_name);
    } else {
        echo 'Invalid code entered';
    }
?>
